此篇說明何謂mapping types以及它的歷史
有沒有曾經想過,在新增一筆document的時候,endpoint中的
_doc到底是什麼?
p.s. 新增資料endpointPUT {index}/_doc/{id}和POST {index}/_doc
考古 - 何謂mapping types
在es的第一版,每一個document存在一個index而且指定一個 mapping type,
mapping type 用來代表document的type,例如:twitter可以有 user 和 tweet type,每一個 mapping type 也會有自己的 fields,每一個document都會有一個 metadata field _type ,存放著此document的 type name
在搜尋時,也可用 type name 來限定搜尋一或多個types, e.g., 指定 user 和 tweet type
GET twitter/user,tweet/_search
{
"query": {
"match": {
"user_name": "kimchy"
}
}
}
結合 _type field 和 document的 _id 會產生 _uid ,所以在單一一個index下,是可以存在有相同的 _id 但在不同的 types
為什麼要移除 mapping types
在同一index不同types下,是可以有相同的field的,例如: user 和 tweet type都有 user_name field,但是 相同的field必須有一樣的mapping定義,
這對於有些情境是希望不同data type時就有點尷尬了,
例如: deleted 欄位希望在某一type是 date data type,但希望在另一type是 boolean data type
此外,如果儲存在同一index但不同types的資料彼此之間是很少或沒有共通的fields,則會產生 數據很分散,且影響了Lucene壓縮documents的效能
如何取代原有 mapping types
一個index一個type,把原本的 user 和 tweet type 變成各自一個index,即 tweets 和 user index,indices間彼此是獨立的,也就可以有不同的field data type
再者,如果真的想保留舊有的 _type ,也可以額外在indices內都定義 type field,
如果原本是 mapping type user的document,則此field值為 user,同理 type tweet 也是
mapping types 推演歷程
Elasticsearch 5.6.0
index.mapping.single_type: true 讓 index只能有單一type,而 6.0開始強制此行為Elasticsearch 6.x
_doc ,因為在7.0會是 _doc
_uid不再是由 _type 和 _id 合併產生,變成 _uid 是 _id 的 alias(別名)include_type_name 預設為 true,則index建立、mapping APIs等都需要指定 type name,而如果indices沒有明確指定type的話,則會使用 type name _doc
Elasticsearch 7.x
type,e.g., 指定id使用的 PUT {index}/_doc/{id} 以及 自動產生id使用的 POST {index}/_doc ,注意的是,7.0的 _doc 是path的常駐部分,代表的是 endpoint name,而不是 document type
include_type_name 預設為 false
Elasticsearch 8.x
include_type_name
整理一下重點 (目前Elasticsearch版本為 7.9.0)
在7.0後,_doc 代表的是 endpoint name,而非 document type
一些APIs中,如 index, get, delete document APIs內的 _doc 是path的常駐部分
requests中指定types已被棄用,但還是可以正常運作,但實際上其 _type 為 _doc
例如:
新增id為1且指定document type為my_type
Reqeust
PUT /my-index-000001/my_type/1
{
"foo": "baz"
}
取得單筆資料
Reqeust
GET /my-index-000001/_doc/1
Response
可發現此筆資料的 _type 為 _doc
小小新手,如有理解錯誤或寫錯再請不吝提醒或糾正
其實很猶豫要不要講這麼仔細,但是我覺得能清楚理解_doc是什麼,對於使用指令會更清楚明瞭